package com.smile.model;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

import sun.rmi.runtime.NewThreadAction;

import com.google.gson.Gson;
import com.smile.server.ChatManager;

public class ChatSocket extends Thread {

	private String name;
	private Socket socket;
	private Gson gson;

	public ChatSocket(String name, Socket socket) {
		this.name = name;
		this.socket = socket;
		this.gson = new Gson();
	}
	
	public String getClientName(){
		return name;
	}

	public void out(String out) {

		try {

			PrintWriter bw = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(),
					"utf-8"));
			bw.write(out);
			bw.flush();

		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void csTouch(){
//		out("连接成功\n");
		System.out.println("连接成功");
	}
	
	public void closeSocket(){
		try {
			this.socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		while (!socket.isClosed()) {
			try {
				BufferedReader br = new BufferedReader(new InputStreamReader(
						socket.getInputStream(), "utf-8"));

				String line = null;
				while ((line = br.readLine()) != null) {
//					ChatManager.getCM().publish(this, str);
					ChatManager.getCM().dealMessage(this, line);
				}
				br.close();

			} catch (IOException e) {
				switch (e.getMessage()) {
				case "socket closed":
					
					break;
 
				default:
					System.out.println("ChatSocket----" + e.getMessage());
					break;
				}
			}
		}
		ChatManager.getCM().del(this);
	}

}
